import asyncio
from pyppeteer import launch


def screen_size():
    """使用tkinter获取屏幕大小"""
    import tkinter
    tk = tkinter.Tk()
    width = tk.winfo_screenwidth()
    height = tk.winfo_screenheight()
    tk.quit()
    return width, height


async def main():
    # headless 展示出页面
    # 取消自动软件控制的展示
    #  userDataDir='./userdata'   保存本地的 Cache、Cookies 等  以便下次使用
    # devtools=True 打开F12
    browser = await launch(headless=False, userDataDir='E:/TempData/', ignoreDefaultArgs=['--enable-automation'])
    page = await browser.newPage()
    width, height = screen_size()
    # 最大化窗口
    await page.setViewport({
        "width": width,
        "height": height
    })
    # 设置浏览器
    await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36')
    # 防止被识别，将webdriver设置为false
    await page.evaluate(
        '''() =>{ Object.defineProperties(navigator,{ webdriver:{ get: () => false } }) }''')

    await page.goto('https://www.qcc.com/user_login?back=%2F')
    await asyncio.sleep(5)
    # 登录时的验证
    normal_login = await page.xpath('//*[@id="normalLogin"]')
    await normal_login[0].click()
    # 滑动验证
    await page.waitFor(1000)
    await try_validation(page)

    await page.waitFor(1000)
    await page.close()


async def try_validation(page, distance=308):
    # 将距离拆分成两段，模拟正常人的行为
    distance1 = distance - 10
    distance2 = 10
    btn_position = await page.evaluate('''
       () =>{
        return {
         x: document.querySelector('#nc_1_n1z').getBoundingClientRect().x,
         y: document.querySelector('#nc_1_n1z').getBoundingClientRect().y,
         width: document.querySelector('#nc_1_n1z').getBoundingClientRect().width,
         height: document.querySelector('#nc_1_n1z').getBoundingClientRect().height
         }}
        ''')
    x = btn_position['x'] + btn_position['width'] / 2
    y = btn_position['y'] + btn_position['height'] / 2
    # print(btn_position)
    await page.mouse.move(x, y)
    await page.mouse.down()
    await page.mouse.move(x + distance1, y, {'steps': 30})
    await page.waitFor(800)
    await page.mouse.move(x + distance1 + distance2, y, {'steps': 20})
    await page.waitFor(800)
    await page.mouse.up()


asyncio.get_event_loop().run_until_complete(main())